package org.wisdom.exception.advice;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.wisdom.exception.BusinessException;
import org.wisdom.vo.ResponseResult;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常
 * 
 * @author zhangzhiyan
 * @date 2021/06/27 18:59
 **/
@RestControllerAdvice
@Slf4j
public class WisdomControllerAdvice {

    /**
     * 业务异常拦截
     * 
     * @author zhangzhiyan
     * @date 2021/06/27 19:05
     * @param e
     *            业务异常
     * @return org.wisdom.cloud.vo.ResponseResult
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult<String> businessException(BusinessException e) {
        log.error("拦截异常：BusinessException", e);
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 异常拦截
     *
     * @author zhangzhiyan
     * @date 2021/06/27 19:05
     * @param e
     *            业务异常
     * @return org.wisdom.cloud.vo.ResponseResult
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseResult<String> exception(Exception e) {
        log.error("拦截异常：Exception", e);
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 运行时异常拦截
     *
     * @author zhangzhiyan
     * @date 2021/06/27 19:05
     * @param e
     *            业务异常
     * @return org.wisdom.cloud.vo.ResponseResult
     */
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseResult<String> runException(RuntimeException e) {
        log.error("拦截异常：RuntimeException", e);
        // 处理持久层根据时间戳判断是否可以进行数据修改的异常提示
        if (e.getCause() != null && e.getCause().getCause() instanceof BusinessException) {
            BusinessException businessException = (BusinessException)e.getCause().getCause();
            int errCode = businessException.getCode();
            String message = businessException.getMessage();
            return ResponseResult.fail(errCode, message);
        } else {
            return ResponseResult.fail(e.getMessage());
        }
    }
}
